import sys

import os
from google.appengine.ext.webapp import template

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
use_library('django', '0.96')
from os import environ
import models
import datetime

class Category(webapp.RequestHandler,db.Model):
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=models.userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		category=[]		
		allcategories=db.GqlQuery("SELECT * FROM projectCategory")
		for spcategory in allcategories:
			tmp=[]
			tmp.append(spcategory.categoryid)
			tmp.append(spcategory.categorytype)
			category.append(tmp)
		path = os.path.join(os.path.dirname(__file__),'category.html')
		self.response.out.write(template.render(path,{"category":category}))

	def post(self):
		category=db.GqlQuery("SELECT * FROM projectCategory")
		for i in category:
			if self.request.get(i.categoryid) != i.categoryid:
				i.delete()

		categoryentry=self.request.get("addcategory")
		categoryentrylist=categoryentry.split(',')
		maximum=self.request.get("maximum")
		maximum=maximum.split(',')
		maxprojs=self.request.get("maxprojects")
		maxprojs=maxprojs.split(',')
		for i in range(0,len(categoryentrylist)):
			if categoryentrylist[i]:
				pf=models.projectCategory(categorytype=str(categoryentrylist[i]),maxmembers=int(maximum[i]),maxprojects=int(maxprojs[i]))
				key=pf.put()
				idnum=key.id()
				pf.categoryid=str(idnum)
				pf.put()
		self.redirect("/admin")

application = webapp.WSGIApplication([('/updatecategory', Category)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
